var profileViewModel;

$(document).ready(function() {
	var editProfileViewModel = new EditProfileViewModel();
	profileViewModel = new ProfileViewModel(editProfileViewModel);
	
	//TODO: Arreglar mas adelante el cropeo. 
	//var avatarViewModel = new AvatarViewModel('image/avatarThumb', 'image/uploadAvatarCrop', profileViewModel.onUploadAvatarSuccess);
	
	ko.applyBindings(profileViewModel, $("#userInformation")[0]);
	
	//TODO: Arreglar mas adelante el cropeo.
	//ko.applyBindings(avatarViewModel, $("#avatarPopin")[0]);
	validateOnChangePassword();
});

function ProfileViewModel(editProfileViewModel, editMarketViewModel) {
	var self = this;
	
	self.profileInfo = ko.observable(new UserInfo(userInfo));
	self.editProfileVM = editProfileViewModel;
	self.avatar = ko.observable(self.profileInfo().avatarPath());
	self.market = ko.observable();
	self.marketImageUrl = ko.observable();
	self.products = ko.observableArray();
	self.marketInfo = ko.observable();
	
	self.deletedProductName = ko.observable();
	self.deletedProductId = ko.observable();
	self.confirmDeletion = function() {
		getService("product/deleteProduct", { productId: self.deletedProductId() }, self.deleteProductSuccess, self.deleteProductFail);
	};
	
	self.deleteProductSuccess = function() {
		restoreInformationAction("productDeletedSuccess");
		self.refreshProducts();
		$('#confirmProductDeletionModal').modal('hide');
	};
	
	self.deleteProductFail = function() {
		restoreInformationAction("productDeletedFail");
		$('#confirmProductDeletionModal').modal('hide');
	};
	
	self.hasMarket = ko.computed(function() {
		return self.market() != undefined;
	});
	
	self.hasActivatedMarket = ko.computed(function() {
		return self.market() != undefined && self.market().enable;
	});
	
	self.hasDesactivatedMarket = ko.computed(function() {
		return self.market() != undefined && !self.market().enable;
	});
	
	self.changePass = function(){
		$('#changePasswordModal').modal('show');
	};
	
	self.cancelChangePassword = function() {
		$('#changePasswordModal').modal('hide');
	};
	
	self.avatarPath = ko.computed(function(){
		return getImagePath('image/avatarThumb', self.avatar(), "large");
	});
	
	self.showUpdateProfilePopin = function() {
		self.editProfileVM.loadInfo(self.profileInfo());
		$('#updateProfileModal').modal('show');
	};
	
	self.goToUpdateMarket = function() {
		redirect('market/marketCreation/' + self.market().id);
	};
	
	self.desactivateMarket = function() {
		$('#confirmMarketDesactivationModal').modal('show');
	};
	
	self.confirmMarketDesactivation = function() {
		getService("market/desactivateMarket", { marketId : self.market().id }, function() {
			restoreInformationAction("marketDesactivationSuccess");
			$('#confirmMarketDesactivationModal').modal('hide');
			var market = self.market();
			market.enable = false;
			self.market(market);
		}, error_handler);
	};
	
	self.activateMarket = function() {
		getService("market/activateMarket", { marketId : self.market().id }, function() {
			var market = self.market();
			market.enable = true;
			self.market(market);
			restoreInformationAction("marketActivationSuccess");
		}, error_handler);
	};
	
	self.editProfileVM.updateProfileSuccess = function (profileUpdated) {
		self.profileInfo(new UserInfo(profileUpdated));
		$('#updateProfileModal').modal('hide');
		restoreInformationAction("userEditionSuccess");
	};
	
	self.onUploadAvatarSuccess = function(fileName){
		getService("user/updateAvatar", { "userId" : self.profileInfo().id, "avatarPath" : fileName }, function(){
			self.avatar(fileName);
			restoreInformationAction("avatarEditionSuccess");
		}, error_handler);
	};
	
	//TODO: Arreglar mas adelante el cropeo.
	self.uploadImage = new UploadImage("#inputAvatarFile", self.onUploadAvatarSuccess);
	
	self.getProductsSuccess = function(products) {
		self.products($.map(products.elements, function (product) { return new Product(product, product.userId == userInfo.id, "small"); }));
	};
	
	self.pager = ko.observable();
	
	getService("market/getMarketByUser", { "userId" : self.profileInfo().id}, function(market) {
		if(market) {
			self.market(market);
			self.marketImageUrl(getImagePath('image/marketThumb', self.market().imagePath, "medium"));
			self.pager(new Pager({ webService: "product/getProductsByEnabledOrDisabledMarketId", params : { "marketId" : self.market().id, "pageSize" : 8 }, onSuccess: self.getProductsSuccess }));
		}
	}, error_handler);
	
	self.showProducts = function(products) {
		$(products).show();
	};
	
	self.refreshProducts = function() {
		self.pager(new Pager({ webService: "product/getProductsByEnabledOrDisabledMarketId", params : { "marketId" : self.market().id, "pageSize" : 8 }, onSuccess: self.getProductsSuccess }));
	};
	
	self.userTransaction = new UserTransactionsViewModel(self.profileInfo().id);
	self.userQuestions = new QuestionsViewModel();
}

function EditProfileViewModel(){
	var self = this;
	
	self.profileInfo = {
		id: 0,
		name: ko.observable(),
		surname: ko.observable(),
		email: ko.observable(),
		avatarPath: ko.observable(),
		phone: ko.observable(),
		address: ko.observable(),
		birthday: ko.observable(),
		genre: ko.observable(),
	};
	
	self.updateProfileSuccess;
	
	self.loadInfo = function(profile) {
		self.profileInfo.id = profile.id;
		self.profileInfo.name(profile.name());
		self.profileInfo.surname(profile.surname());
		self.profileInfo.email(profile.email());
		self.profileInfo.avatarPath(profile.avatarPath());
		self.profileInfo.phone(profile.phone());
		self.profileInfo.address(profile.address());
		self.profileInfo.birthday(profile.birthday());
		self.profileInfo.genre(profile.genre());
	};
	
	self.save = function(){
		var userParams = ko.toJSON({ id: self.profileInfo.id,
			name: self.profileInfo.name(),
			surname: self.profileInfo.surname(),
			email: self.profileInfo.email(),
			birthdayString: self.profileInfo.birthday(),
			phone: self.profileInfo.phone(),
			address: self.profileInfo.address(),
			genre: self.profileInfo.genre()});
		
		postService("user/editUser", userParams, function() {
			var info = {
				id: self.profileInfo.id,
				name: self.profileInfo.name(),
				surname: self.profileInfo.surname(),
				email: self.profileInfo.email(),
				avatarPath: self.profileInfo.avatarPath(),
				phone: self.profileInfo.phone(),
				address: self.profileInfo.address(),
				formattedBirthday: self.profileInfo.birthday(),
				genre: self.profileInfo.genre(),
			};
			
			self.updateProfileSuccess(info);
		}, error_handler);
	};
}

function UserInfo(info) {
	var self = this;
	self.id = info.id;
	self.name = ko.observable(info.name);
	self.surname = ko.observable(info.surname);
	self.fullName = ko.observable(info.name + " " + info.surname);
	self.email = ko.observable(info.email);
	self.phone = ko.observable(info.phone);
	self.address = ko.observable(info.address);
	self.birthday = ko.observable(info.formattedBirthday);
	self.genre = ko.observable(info.genre);
	self.isMale = ko.observable(info.genre === 'M');
	self.avatarPath = ko.observable(info.avatarPath);
}

function restoreInformationAction(itemToShow) {
	$("#userEditionSuccess").hide();
	$("#avatarEditionSuccess").hide();
	$("#avatarEditionFail").hide();
	
	$("#marketCreationSuccess").hide();
	$("#marketEditionSuccess").hide();
	$("#marketEditionFails").hide();
	$("#marketActivationSuccess").hide();
	$("#marketDesactivationSuccess").hide();
	
	$("#productEditionSuccess").hide();
	$("#productDeletedSuccess").hide();
	$("#productDeletedFail").hide();
	
	if(itemToShow) {
		$("#" + itemToShow).show();
	}
};

function validateOnChangePassword() {
	$("#changePassForm").validate({
		rules: {
			'password_old': { required: true, minlength: 5 },
			'password_new': { required: true, minlength: 5 },
			'password_confirm' : { required: true, minlength: 5, equalTo: "#password_new" }
		},
		messages: {
			'password_old': { required: 'Debe ingresar el password', minlength: 'El password debe tener mas de 5 caracteres' },
			'password_new': { required: 'Debe ingresar el password', minlength: 'El password debe tener mas de 5 caracteres' },
			'password_confirm': { required: 'Debe ingresar el password', minlength: 'El password debe tener mas de 5 caracteres', equalTo: 'Los password no coinciden' },
		}
	});
}